package com.goldenautumn.prefabricate.activity.cart

import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.cart.dialog.CidDialog
import com.goldenautumn.prefabricate.activity.cart.dialog.PaymentMethodDialog
import com.goldenautumn.prefabricate.activity.mine.address.AddressManageActivity
import com.goldenautumn.prefabricate.business.entity.AddressInfoVo
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSkuVo
import com.goldenautumn.prefabricate.business.entity.OrderKeyValue
import com.goldenautumn.prefabricate.business.entity.PaymentMethodVo
import com.goldenautumn.prefabricate.business.order.OrderPayUiState
import com.goldenautumn.prefabricate.business.order.OrderStatusUiState
import com.goldenautumn.prefabricate.business.order.OrderViewModel
import com.goldenautumn.prefabricate.databinding.ActivitySettlementBinding
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.getUserInfo
import com.goldenautumn.prefabricate.utils.loadImgUrl
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.goldenautumn.prefabricate.wxapi.WXPayEntryActivity
import com.google.gson.reflect.TypeToken
import com.gyf.immersionbar.ImmersionBar
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.compat.visible
import qncx.external.common.utils.intent

class SettlementActivity : BaseActivity<ActivitySettlementBinding>() {

    private val mGoodsAdapter by lazy {
        SettlementGoodsAdapter()
    }

    var launcher =  registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
        if(result.resultCode == RESULT_OK) {
            result.data?.let {
                address = result.data?.extras?.getSerializable(BUSINESS_PAGE_DATA) as AddressInfoVo
                setAddressUI()
            }
        }
    }

    private val mOrderModel by viewModels<OrderViewModel>()

    private var payment : PaymentMethodVo? = null

    private var address : AddressInfoVo? = null

    private val carID:String?
        get() = intent.getStringExtra(BUSINESS_PAGE_DATA)

    private val orderID:String?
        get() = intent.getStringExtra("ORDER")


    override fun getLayoutId(): Int = R.layout.activity_settlement

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        initToolbarNav(mBinding.toolbar,true)

        mBinding.goodsRv.layoutManager = LinearLayoutManager(this)
        mBinding.goodsRv.adapter = mGoodsAdapter

        mBinding.addAddress.setOnClickListener {
            launcher.launch(AddressManageActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,0))
        }

        mBinding.addressBody.setOnClickListener {
          if(orderID == null)
            launcher.launch(AddressManageActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,if(address?.address_id == null) 0 else address?.address_id))
        }

        mBinding.idBody.setOnClickListener {
            CidDialog{

            }.onShow(supportFragmentManager.beginTransaction())
        }

        mBinding.addCid.setOnClickListener {
            CidDialog{
                mBinding.idBody.visible()
                mBinding.addCid.gone()
            }.onShow(supportFragmentManager.beginTransaction())
        }

        mBinding.paymentMethods.setOnClickListener {
//            if(orderID == null)
            PaymentMethodDialog(payment) {
                payment = it
                it?.icon?.let { it1 -> mBinding.paymentMethods.setLeftIcon(it1) }
                mBinding.paymentMethods.setLeftString(it?.title)
                mBinding.paymentMethods.setLeftTextColor(ContextCompat.getColor(this,R.color.color_1D1F20))
            }.onShow(supportFragmentManager.beginTransaction())
        }

        getUserInfo().address?.let {
            address = GsonUtils.fromJson(it, object : TypeToken<AddressInfoVo>() {}.type)
            setAddressUI()
        }

        mBinding.shapeButton.setOnClickListener {
            if(address == null) {
                onCenterToast(getString(R.string.car_address_prompt))
                return@setOnClickListener
            }
            if(payment == null) {
                onCenterToast(getString(R.string.car_pay_prompt))
                return@setOnClickListener
            }
            if(carID != null) mOrderModel.getCarPreview("$carID","POST",payment?.value)
            else if(orderID != null) mOrderModel.onOrderPay("$orderID","${payment?.value}")
        }

        if(carID != null) mOrderModel.getCarPreview("$carID","GET")
        if(orderID != null) mOrderModel.onOrderDetails("$orderID")

        while (isActive) {
            select {
                mOrderModel.orderPayUiState.onReceive {
                    when(it) {
                        is OrderPayUiState.CarPreview -> {
                            address = it.preview?.address
                            setAddressUI()
                            mGoodsAdapter.submitList(it.preview.goods_list)
                            mBinding.itemsPrice.text = "${(String.format(getString(R.string.currency), "${it.preview?.order_total_price}"))}"
                            mBinding.subtotal.text = "${(String.format(getString(R.string.currency), "${it.preview?.order_price}"))}"
                            mBinding.totalPrice.text = "${(String.format(getString(R.string.currency), "${it.preview?.order_pay_price}"))}"
                            mBinding.shipping.text = "${(String.format(getString(R.string.currency), "${it.preview?.express_price}"))}"
                            mBinding.discount.text = "${if(it.preview?.coupon_money ?:0 > 0) "-${(String.format(getString(R.string.currency), "${it.preview?.coupon_money}"))}" else "0"}"
                            SPUtils.getInstance().put("PRICE",it.preview?.order_pay_price)
                        }
                        is OrderPayUiState.PlayResult -> {
                            startActivity(WXPayEntryActivity::class.intent.putExtra(BUSINESS_PAGE_DATA,if(it.isSuccess) "9000" else "${it.msg}"))
                            finish()
                        }
                        else -> {}
                    }
                }
                mOrderModel.orderStatusUiState.onReceive {
                    when (it) {
                        is OrderStatusUiState.OrderDetails -> {
                            address = it.order?.address
                            setAddressUI()
                            var goods = ArrayList<GoodsInfoVO>()
                            it.order?.goods?.forEach {
                                goods.add(GoodsInfoVO(goods_image = it.image?.file_path,goods_name = it.goods_name,goods_sku = GoodsSkuVo(goods_attr = it.goods_attr,goods_price = it.goods_price),total_num = it.total_num))
                            }
                            mGoodsAdapter.submitList(goods)
                            mBinding.itemsPrice.text = "${(String.format(getString(R.string.currency), "${it.order.total_price}"))}"
                            mBinding.subtotal.text = "${(String.format(getString(R.string.currency), "${it.order?.order_price}"))}"
                            mBinding.totalPrice.text = "${(String.format(getString(R.string.currency), "${it.order?.pay_price}"))}"
                            mBinding.shipping.text = "${(String.format(getString(R.string.currency), "${it.order?.express_price}"))}"
                            mBinding.discount.text = "${if((it.order?.coupon_money ?:"0L").toFloat() > 0) "-${(String.format(getString(R.string.currency), "${it.order?.coupon_money}"))}" else "0"}"
                            SPUtils.getInstance().put("PRICE",it.order?.pay_price)

                            payment = formatPayMethod(it.order.pay_type)
                            payment?.icon?.let { it1 -> mBinding.paymentMethods.setLeftIcon(it1) }
                            mBinding.paymentMethods.setLeftString(payment?.title)
                            mBinding.paymentMethods.setLeftTextColor(ContextCompat.getColor(this@SettlementActivity,R.color.color_1D1F20))
//                            mBinding.paymentMethods.setRightIcon(null)
                            mBinding.address.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null)
                            mBinding.shapeButton.setText(R.string.keep_paying)
                        }
                        else -> {}
                    }
                }
            }
        }
    }

    fun setAddressUI(){
        address?.let {
            mBinding.textView4.gone()
            mBinding.addAddress.gone()
            mBinding.addressBody.visible()
            mBinding.nickName.text = "${address?.name}"
            mBinding.phone.text = "${address?.phone}"
            mBinding.address.text = "${address?.detail}"
            mBinding.city.text = "${address?.region?.province},${address?.region?.city},${address?.region?.region}"
        }
    }

    fun formatPayMethod(type:OrderKeyValue?) : PaymentMethodVo?{
        when (type?.value) {
            "10" -> {
                return PaymentMethodVo("${type.value}", R.mipmap.ic_pay_balance,"${type.text}")
            }
            "20" -> {
                return PaymentMethodVo("${type.value}", R.mipmap.ic_payment_method_wechat,"${type.text}")
            }
            "30" -> {
                return PaymentMethodVo("${type.value}", R.mipmap.ic_payment_method_ali,"${type.text}")
            }
            else -> return null
        }
    }

}